<template>
  <div class="experience-edit">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>{{ formData.id ? "编辑体验项目" : "添加体验项目" }}</span>
          <el-button-group>
            <el-button @click="handleBack">返回</el-button>
            <el-button type="primary" @click="handleSubmit" :loading="saving"
              >保存</el-button
            >
          </el-button-group>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="120px"
        class="edit-form"
      >
        <el-row :gutter="20">
          <el-col :span="16">
            <!-- 基本信息 -->
            <div class="form-section">
              <h3 class="section-title">基本信息</h3>
              <el-form-item label="项目名称" prop="title">
                <el-input
                  v-model="formData.title"
                  placeholder="请输入项目名称"
                />
              </el-form-item>
              <el-form-item label="项目分类" prop="categoryId">
                <el-select
                  v-model="formData.categoryId"
                  placeholder="请选择分类"
                >
                  <el-option
                    v-for="item in categories"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="项目简介" prop="description">
                <el-input
                  v-model="formData.description"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入项目简介"
                />
              </el-form-item>
              <el-form-item label="项目标签" prop="tags">
                <el-select
                  v-model="formData.tags"
                  multiple
                  filterable
                  allow-create
                  default-first-option
                  placeholder="请选择或输入标签"
                >
                  <el-option
                    v-for="tag in tagOptions"
                    :key="tag"
                    :label="tag"
                    :value="tag"
                  />
                </el-select>
              </el-form-item>
            </div>

            <!-- 价格和预约 -->
            <div class="form-section">
              <h3 class="section-title">价格和预约</h3>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="体验价格" prop="price">
                    <el-input-number
                      v-model="formData.price"
                      :min="0"
                      :precision="2"
                      :step="10"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="最大容量" prop="capacity">
                    <el-input-number
                      v-model="formData.capacity"
                      :min="1"
                      :step="1"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-form-item label="体验时长" prop="duration">
                <el-input-number
                  v-model="formData.duration"
                  :min="0.5"
                  :step="0.5"
                  :precision="1"
                  style="width: 200px"
                />
                <span class="unit-text">小时</span>
              </el-form-item>
              <el-form-item label="服务时间" prop="serviceTimes">
                <el-time-select
                  v-model="formData.serviceTimes"
                  start="08:00"
                  step="00:30"
                  end="22:00"
                  multiple
                  placeholder="请选择可预约时间段"
                />
              </el-form-item>
            </div>

            <!-- 详细内容 -->
            <div class="form-section">
              <h3 class="section-title">详细内容</h3>
              <el-form-item label="体验地点" prop="location">
                <el-input
                  v-model="formData.location"
                  placeholder="请输入体验地点"
                />
              </el-form-item>
              <el-form-item label="注意事项" prop="notices">
                <el-input
                  v-model="formData.notices"
                  type="textarea"
                  :rows="4"
                  placeholder="请输入注意事项"
                />
              </el-form-item>
              <el-form-item label="详细介绍" prop="content">
                <el-input
                  v-model="formData.content"
                  type="textarea"
                  :rows="6"
                  placeholder="请输入详细介绍"
                />
              </el-form-item>
            </div>
          </el-col>

          <el-col :span="8">
            <!-- 封面图片 -->
            <div class="form-section">
              <h3 class="section-title">封面图片</h3>
              <el-form-item prop="cover">
                <el-upload
                  class="cover-uploader"
                  :show-file-list="false"
                  :on-success="handleCoverSuccess"
                  :before-upload="beforeCoverUpload"
                >
                  <img
                    v-if="formData.cover"
                    :src="formData.cover"
                    class="cover-image"
                  />
                  <el-icon v-else class="cover-uploader-icon"><Plus /></el-icon>
                </el-upload>
                <div class="upload-tip">
                  建议尺寸：800x600px，支持 jpg、png 格式
                </div>
              </el-form-item>
            </div>

            <!-- 详情图片 -->
            <div class="form-section">
              <h3 class="section-title">详情图片</h3>
              <el-form-item prop="images">
                <el-upload
                  :file-list="formData.images"
                  list-type="picture-card"
                  :on-preview="handlePictureCardPreview"
                  :on-remove="handleRemove"
                  :on-success="handleImageSuccess"
                  :before-upload="beforeImageUpload"
                >
                  <el-icon><Plus /></el-icon>
                </el-upload>
              </el-form-item>
            </div>

            <!-- 其他设置 -->
            <div class="form-section">
              <h3 class="section-title">其他设置</h3>
              <el-form-item label="排序" prop="sort">
                <el-input-number
                  v-model="formData.sort"
                  :min="0"
                  :max="999"
                  style="width: 100%"
                />
              </el-form-item>
              <el-form-item label="状态" prop="status">
                <el-switch
                  v-model="formData.status"
                  :active-value="'active'"
                  :inactive-value="'inactive'"
                  active-text="上架"
                  inactive-text="下架"
                />
              </el-form-item>
            </div>
          </el-col>
        </el-row>
      </el-form>

      <!-- 图片预览 -->
      <el-dialog v-model="previewVisible">
        <img
          w-full
          :src="previewUrl"
          alt="Preview Image"
          style="max-width: 100%"
        />
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import { useRoute, useRouter } from "vue-router";
import service from "@/api/axios";

const route = useRoute();
const router = useRouter();

// 表单数据
const formRef = ref(null);
const formData = reactive({
  id: "",
  title: "",
  categoryId: "",
  description: "",
  tags: [],
  price: 0,
  capacity: 1,
  duration: 1,
  serviceTimes: [],
  location: "",
  notices: "",
  content: "",
  cover: "",
  images: [],
  sort: 0,
  status: "active",
});

// 分类选项
const categories = ref([]);

// 标签选项
const tagOptions = ref([
  "亲子互动",
  "团建活动",
  "传统文化",
  "非遗体验",
  "户外活动",
]);

// 表单验证规则
const rules = {
  title: [
    { required: true, message: "请输入项目名称", trigger: "blur" },
    { min: 2, max: 50, message: "长度在 2 到 50 个字符", trigger: "blur" },
  ],
  categoryId: [
    { required: true, message: "请选择项目分类", trigger: "change" },
  ],
  description: [
    { required: true, message: "请输入项目简介", trigger: "blur" },
    { max: 200, message: "不能超过 200 个字符", trigger: "blur" },
  ],
  price: [{ required: true, message: "请输入体验价格", trigger: "blur" }],
  capacity: [{ required: true, message: "请输入最大容量", trigger: "blur" }],
  duration: [{ required: true, message: "请输入体验时长", trigger: "blur" }],
  location: [{ required: true, message: "请输入体验地点", trigger: "blur" }],
  content: [{ required: true, message: "请输入详细介绍", trigger: "blur" }],
  cover: [{ required: true, message: "请上传封面图片", trigger: "change" }],
};

// 状态
const saving = ref(false);
const previewVisible = ref(false);
const previewUrl = ref("");

// 获取分类列表
const fetchCategories = async () => {
  try {
    const res = await service.get('/admin/experiences/categories', {
      params: { pageSize: 100 }
    });
    if (res.code === 200 && res.data) {
      categories.value = res.data.list || [];
    } else {
      // 使用测试数据
      categories.value = [
        { id: 1, name: "文化体验" },
        { id: 2, name: "手工艺" },
        { id: 3, name: "农事体验" },
        { id: 4, name: "美食制作" },
      ];
    }
  } catch (error) {
    console.error("获取分类列表失败", error);
    // 使用测试数据
    categories.value = [
      { id: 1, name: "文化体验" },
      { id: 2, name: "手工艺" },
      { id: 3, name: "农事体验" },
      { id: 4, name: "美食制作" },
    ];
  }
};

// 获取详情
const fetchDetail = async (id) => {
  try {
    const res = await service.get(`/admin/experiences/${id}`);
    
    if (res.code === 200 && res.data) {
      // 处理API返回数据
      const data = res.data;
      
      // 转换标签数据，如果存在
      if (data.tags && Array.isArray(data.tags)) {
        data.tags = data.tags.map(tag => tag.tagName || tag);
      }
      
      // 转换服务时间数据，如果存在
      if (data.serviceTimes && Array.isArray(data.serviceTimes)) {
        data.serviceTimes = data.serviceTimes.map(time => time.serviceTime || time);
      }
      
      // 转换图片数据，如果存在
      if (data.images && Array.isArray(data.images)) {
        data.images = data.images.map(img => ({
          name: img.name || '图片',
          url: img.imageUrl || img.url
        }));
      }
      
      // 转换时长数据
      if (data.duration) {
        data.duration = parseFloat(data.duration);
      }
      
      Object.assign(formData, data);
    } else {
      // 使用测试数据
      Object.assign(formData, {
        id: 1,
        title: "贵港传统手工艺体验",
        categoryId: 2,
        description: "体验贵港传统手工艺制作过程",
        tags: ["传统文化", "非遗体验"],
        price: 88,
        capacity: 20,
        duration: 2,
        serviceTimes: ["09:00", "14:00", "16:00"],
        location: "贵港市文化中心",
        notices: "请提前10分钟到达，自备工具",
        content: "详细介绍内容...",
        cover: "https://example.com/cover.jpg",
        images: [],
        sort: 1,
        status: "active",
      });
    }
  } catch (error) {
    console.error("获取详情失败", error);
    ElMessage.error("获取详情失败");
    // 使用测试数据
    Object.assign(formData, {
      id: 1,
      title: "贵港传统手工艺体验",
      categoryId: 2,
      description: "体验贵港传统手工艺制作过程",
      tags: ["传统文化", "非遗体验"],
      price: 88,
      capacity: 20,
      duration: 2,
      serviceTimes: ["09:00", "14:00", "16:00"],
      location: "贵港市文化中心",
      notices: "请提前10分钟到达，自备工具",
      content: "详细介绍内容...",
      cover: "https://example.com/cover.jpg",
      images: [],
      sort: 1,
      status: "active",
    });
  }
};

// 返回列表
const handleBack = () => {
  router.push("/admin/content/experiences/list");
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();
    saving.value = true;

    // 准备提交数据
    const submitData = { ...formData };
    
    // 判断是新增还是编辑
    const isEdit = !!formData.id;
    let res;
    
    if (isEdit) {
      // 编辑
      res = await service.put(`/admin/experiences/${formData.id}`, submitData);
    } else {
      // 新增
      res = await service.post('/admin/experiences', submitData);
    }
    
    if (res.code === 200) {
      ElMessage.success(formData.id ? "更新成功" : "添加成功");
      router.push("/admin/content/experiences");
    } else {
      ElMessage.error(res.message || "保存失败");
    }
  } catch (error) {
    console.error("保存失败", error);
    // 表单验证失败或请求失败
    if (error.message) {
      ElMessage.error(error.message);
    }
  } finally {
    saving.value = false;
  }
};

// 封面图片上传
const handleCoverSuccess = (response) => {
  // 确保响应中包含url字段
  if (response && response.data && response.data.url) {
    formData.cover = response.data.url;
  } else if (response && response.url) {
    formData.cover = response.url;
  } else {
    // 假设上传成功但响应格式不符合预期
    formData.cover = "https://example.com/uploaded-cover.jpg";
    console.warn("上传响应格式不符合预期", response);
  }
};

const beforeCoverUpload = (file) => {
  const isImage = file.type.startsWith("image/");
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isImage) {
    ElMessage.error("只能上传图片文件！");
    return false;
  }
  if (!isLt2M) {
    ElMessage.error("图片大小不能超过 2MB！");
    return false;
  }
  return true;
};

// 详情图片上传
const handleImageSuccess = (response, uploadFile) => {
  // 确保响应中包含url字段
  let imageUrl = "";
  if (response && response.data && response.data.url) {
    imageUrl = response.data.url;
  } else if (response && response.url) {
    imageUrl = response.url;
  } else {
    // 假设上传成功但响应格式不符合预期
    imageUrl = "https://example.com/uploaded-image.jpg";
    console.warn("上传响应格式不符合预期", response);
  }
  
  formData.images.push({
    name: uploadFile.name,
    url: imageUrl,
  });
};

const handleRemove = (uploadFile) => {
  const index = formData.images.findIndex(
    (file) => file.url === uploadFile.url,
  );
  if (index > -1) {
    formData.images.splice(index, 1);
  }
};

const handlePictureCardPreview = (uploadFile) => {
  previewUrl.value = uploadFile.url;
  previewVisible.value = true;
};

const beforeImageUpload = (file) => {
  const isImage = file.type.startsWith("image/");
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isImage) {
    ElMessage.error("只能上传图片文件！");
    return false;
  }
  if (!isLt2M) {
    ElMessage.error("图片大小不能超过 2MB！");
    return false;
  }
  return true;
};

// 初始化
onMounted(() => {
  fetchCategories();
  const id = route.query.id;
  if (id) {
    fetchDetail(id);
  }
});
</script>

<style scoped>
.experience-edit {
  padding: 20px;
  background-color: var(--el-bg-color-page);
  min-height: calc(100vh - 40px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid var(--el-border-color-light);
}

.form-section {
  background-color: var(--el-bg-color);
  border-radius: 8px;
  padding: 24px;
  margin-bottom: 24px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  margin: 0 0 24px;
  color: var(--el-text-color-primary);
  display: flex;
  align-items: center;
  gap: 8px;
}

.section-title::before {
  content: "";
  width: 4px;
  height: 16px;
  background-color: var(--el-color-primary);
  border-radius: 2px;
}

.edit-form {
  margin-top: 20px;
}

.unit-text {
  margin-left: 10px;
  color: var(--el-text-color-regular);
}

.cover-uploader {
  border: 2px dashed var(--el-border-color);
  border-radius: 8px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration);
}

.cover-uploader:hover {
  border-color: var(--el-color-primary);
  background-color: var(--el-color-primary-light-9);
}

.cover-uploader-icon {
  font-size: 28px;
  color: var(--el-text-color-secondary);
  width: 100%;
  height: 200px;
  text-align: center;
  display: flex;
  justify-content: center;
  align-items: center;
}

.cover-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
  display: block;
  border-radius: 8px;
}

.upload-tip {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  margin-top: 8px;
  line-height: 1.5;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-input-number) {
  width: 100%;
}

:deep(.el-upload--picture-card) {
  --el-upload-picture-card-size: 120px;
  border-radius: 8px;
}

:deep(.el-upload-list--picture-card .el-upload-list__item) {
  border-radius: 8px;
}

:deep(.el-textarea__inner) {
  font-family: var(--el-font-family);
  line-height: 1.6;
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-time-select) {
  width: 100%;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .el-form-item {
    margin-bottom: 18px;
  }

  :deep(.el-form-item__label) {
    float: none;
    display: block;
    text-align: left;
    margin-bottom: 8px;
  }

  .cover-uploader-icon,
  .cover-image {
    height: 160px;
  }
}
</style>
